package com.octopus.optiworks.service;

import org.apache.shiro.SecurityUtils;

import com.octopus.optiworks.dao.RoleDao;
import com.octopus.optiworks.dao.UserDao;
import com.octopus.optiworks.model.EmployeeRole;
import com.octopus.optiworks.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Transactional
@Service("userService")
public class UserService {

	@Autowired
    private UserDao userDao;

	@Autowired
    private RoleDao roleDao;

    public Employee getCurrentUser() {
        final Long currentUserId = (Long) SecurityUtils.getSubject().getPrincipal();
        if( currentUserId != null ) {
            return getUser(currentUserId);
        } else {
            return null;
        }
    }
    
    public boolean hasRole(String role){
    	return SecurityUtils.getSubject().hasRole(role);
    }
    
    public void createRole(EmployeeRole role) {
    	roleDao.save(role);
    }

    public List<EmployeeRole> getAllRoles() {
        return roleDao.loadAll();
    }

    public EmployeeRole getRole(Long roleId) {
        return roleDao.get(roleId);
    }

    public void deleteRole(Long roleId) {
    	roleDao.deleteByKey(roleId);
    }

    public void updateRole(EmployeeRole role) {
    	roleDao.saveOrUpdate(role);
    }
    
    public void createUser(Employee user, boolean signup) {
    	if(signup){
	    	EmployeeRole role = new EmployeeRole(new Long(EmployeeRole.ROLE_USER));
	    	Set<EmployeeRole> roles = new HashSet<EmployeeRole>();
	    	roles.add(role);
	    	user.setRoles(roles);
    	}
    	userDao.save(user);
    }

    public List<Employee> getAllUsers() {
        return userDao.loadAll();
    }

    public Employee getUser(Long userId) {
        return userDao.get(userId);
    }

    public void deleteUser(Long userId) {
    	userDao.deleteByKey(userId);
    }

    public void updateUser(Employee user) {
    	userDao.saveOrUpdate(user);
    }

}
